
declare const wx;
declare const canvas;


const WxOpenDataKeys={
    Grade:"grade"
}

const WxDomainAction={
    FetchFriend : 1,
    FetchGroup : 2,
    Paging : 3,
    UpdateScore:4,
    UpdateAndFetchFriend : 5,
    FetchHistoryScore:6,
}

 

const PAGE_SIZE=6;


function wxShare(){
    if(CC_WECHATGAME){
        wx.shareAppMessage(function () {
            return {
              title: '我正在玩这游戏...',
              imageUrl: canvas.toTempFilePathSync({
                destWidth: 500,
                destHeight: 400
              })
            }
          })
    }
}

function wxSetUserCloudStorage(kvDatas){
    cc.log(kvDatas);
    return new Promise((s,r)=>{
        wx.setUserCloudStorage({
            KVDataList:kvDatas,
            success:res => {
                cc.log('success',res);
                s(res);
           
            },
            fail:res => {
                cc.log('error',res);
                r(res);
            },
        });
    });
}

function wxPostMessageToSubDomain(msgObj)
{
    if (CC_WECHATGAME) {
        cc.log('post...',msgObj);
        const openDataContext = wx.getOpenDataContext();
        openDataContext.postMessage(msgObj);
    }
 
}

function wxGetSharedCanvas()
{
    return wx.getOpenDataContext().canvas;
}

function wxGetUserInfo(){
    return new Promise(s=>{
        wx.getUserInfo({
            openIdList: ['selfOpenId'],
            success: (userRes) => {
                cc.log('success',userRes);
                s(userRes.data[0]);
            },
            error:(error)=>{
                cc.log('error',error);
                return Promise.reject(error);
            }});
    });
}


function wxLogin(){
    return new Promise((s,r)=>{
        wx.login({
            success: async (res) => {
                cc.log(res);
                if(res.code){ 
                    s(res);
                }
                else{
                    r(res.errMsg);
                }
            },
            error:(error)=>{
                cc.log('error',error);
                r(error);
            }});
    });
}



  
function wxGetUserCloudStorage(keyList){
    return new Promise((s,r)=>{
        wx.getUserCloudStorage({
            keyList:keyList,
            success:res => {
                cc.log('success',res);
                if(res.KVDataList.length===0){
                    s(null);
                }
                else{
                    s(res.KVDataList);
                }
            },
            fail:res => {
                cc.log('error',res);
              r(res);
            },
        });
    });
}

function wxGetFriendCloudStorage(){
    return new Promise(s=>{
        wx.getFriendCloudStorage({
            keyList:[WxOpenDataKeys.Grade],
            success:res => {
                s(res.data);
            },
            fail:res => {
                cc.log('error',res);
              return Promise.reject(res);
            },
        });
    });
}

function drawRankItemGrid(ctx,index, rank, data, pageLen){
    cc.log(data);
    const avatarUrl = data.avatarUrl;
    data.nickname?null:data.nickname=data.nickName;
    const nick = data.nickname.length <= 10 ? data.nickname : data.nickname.substr(0, 10) + "...";
    let grade;
    if(data.score){
        grade=data.score;
    }
    else{
        const kvData = data.KVDataList.find(kvData => kvData.key === WxOpenDataKeys.Grade);
        grade = kvData ? kvData.value : 0;
    }
    
    const itemGapY = PAGE_SIZE * index;

  

    ctx.fillStyle = "#D8AD51";
    ctx.textAlign = "right";
    ctx.baseLine = "middle";
    ctx.font = "30px Helvetica";


    ctx.fillText(`${rank}`, 50, 52 + itemGapY,20);

    const avatarImg = wx.createImage();
    avatarImg.src = avatarUrl;
    avatarImg.onload = () => {
        if(index + 1 > pageLen)
        {
            return;
        }
        ctx.drawImage(avatarImg, 90, 10 + itemGapY, 60,60);
    };

      //名字
      ctx.fillStyle = "#ffffff";
      ctx.textAlign = "left";
      ctx.baseLine = "middle";
      ctx.font = "20px Helvetica";
      ctx.fillText(nick, 180, 52 + itemGapY,180);

        //分数
        ctx.fillStyle = "#ffffff";
        ctx.textAlign = "left";
        ctx.baseLine = "middle";
        ctx.font = "20px Helvetica";
        ctx.fillText(`${grade}分`, 380, 52 + itemGapY,120);

}

function setError(ctx){
    ctx.clearRect(0, 0, 1000, 1000);
    ctx.fillStyle = "#ffffff";
    ctx.baseLine = "middle";
    ctx.font = "40px Helvetica";
    ctx.fillText(`请求失败`, 190, 200);
}

function setLoading(ctx){
    ctx.clearRect(0, 0, 1000, 1000);
    ctx.fillStyle = "#ffffff";
    ctx.baseLine = "middle";
    ctx.font = "40px Helvetica";
    ctx.fillText(`拼命加载中...`, 180, 200);
}

function setEmpty(ctx){
    ctx.clearRect(0, 0, 1000, 1000);
    ctx.fillStyle = "#ffffff";
    ctx.baseLine = "middle";
    ctx.font = "40px Helvetica";
    ctx.fillText(`暂无最新记录`, 182, 200);
}
 

function showPagedRanks(ctx,page,gameDatas){

    const pageStart = page * PAGE_SIZE;
    const pagedData = gameDatas.slice(pageStart, pageStart + PAGE_SIZE);
    const pageLen = pagedData.length;

    ctx.clearRect(0, 0, 1000, 1000);
    for(let i = 0, len = pagedData.length; i < len; i++)
    {
        this.drawRankItemGrid(ctx,i, pageStart + i + 1, pagedData[i], pageLen);
    }
}

function getTotalPage(length){
    return Math.ceil(length / PAGE_SIZE);
}

 
 


export default{
    WxDomainAction,
    WxOpenDataKeys,
    wxSetUserCloudStorage,
    wxPostMessageToSubDomain,
    wxGetSharedCanvas,
    wxGetUserInfo,
    wxGetUserCloudStorage,
    wxGetFriendCloudStorage,
    wxLogin,
    wxShare,
    ranking:{
        setError,
        setLoading,
        setEmpty,
        showPagedRanks,
        drawRankItemGrid,
        getTotalPage
    }
}